/**
 * @projectName: dataAccessFactory
 * @author: 小飞
 * @description: TODO
 * @date: 2024/2/27 17:34
 * @version: 1.0
 */
package com.home.filter;

import com.home.constant.JwtConstant;
import com.home.constant.MessageConstant;
import com.home.constant.TokenConstant;
import com.home.entity.LoginUser;
import com.home.properties.JwtProperties;
import com.home.result.OutResponse;
import com.home.result.ResultCode;
import com.home.utils.JwtUtil;
import com.home.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JwtTokenUserFilter extends OncePerRequestFilter {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(jwtProperties.getUserTokenName());
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        } catch (Exception e) {
            OutResponse.getResponse(response,ResultCode.NOT_LOGIN.getCode(),MessageConstant.TOKEN_TIMEOUT);
        }

        Long uId = Long.valueOf(claims.get(JwtConstant.U_ID).toString());
        LoginUser loginUser = redisUtil.getRedisObject(TokenConstant.USER_TOKEN_SECRET + uId);
        if (Objects.isNull(loginUser)) {
            OutResponse.getResponse(response,ResultCode.NOT_LOGIN.getCode(),MessageConstant.TOKEN_UN_USED);
        }
        //存入securityHolder中
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}
